import React, { useEffect, useState } from 'react'
import { Card, Button, Table, Form, Modal, Pagination } from 'antd'
import axios from '../../axios/index'
import BaseForm from '../../components/BaseForm'
import Utils from '../../utils/utils'

const Order = () => {
  const [list, setList] = useState([])
  const [selectedItem, setSelectedItem] = useState(null)
  const [visible, setVisible] = useState(false)
  const [pagination, setPagination] = useState(1)
  const [orderInfo, setOrderInfo] = useState(null)

  const handleFilter = (params) => {
    // this.params = params;
    // this.requestList();
  }

  const onCreate = (values) => {
    console.log(orderInfo)
    setVisible(false);
  }

  const openOrderDetail = () => {
    let item = selectedItem;
    if (!item) {
      Modal.info({
        title: '信息',
        content: '请先选择一条订单'
      })
      return;
    }
    window.open(`/#/common/order/detail/${item[0].id}`, '_blank')
  }

  const formList = [
    {
      type: 'SELECT',
      label: '城市',
      field: 'city',
      placeholder: '全部',
      initialValue: '1',
      width: 80,
      list: [{ id: '0', name: '全部' }, { id: '1', name: '北京' }, { id: '2', name: '天津' }, { id: '3', name: '上海' }]
    },
    {
      type: '时间查询'
    },
    {
      type: 'SELECT',
      label: '订单状态',
      field: 'order_status',
      placeholder: '全部',
      initialValue: '1',
      width: 80,
      list: [{ id: '0', name: '全部' }, { id: '1', name: '进行中' }, { id: '2', name: '结束行程' }]
    }
  ]

  const columns = [
    {
      title: '订单编号',
      dataIndex: 'order_sn'
    },
    {
      title: '车辆编号',
      dataIndex: 'bike_sn'
    },
    {
      title: '用户名',
      dataIndex: 'user_name'
    },
    {
      title: '手机号',
      dataIndex: 'mobile'
    },
    {
      title: '里程',
      dataIndex: 'distance',
      render(distance) {
        return distance / 1000 + 'Km';
      }
    },
    {
      title: '行驶时长',
      dataIndex: 'total_time',
      render: Utils.formateDate
    },
    {
      title: '状态',
      dataIndex: 'status',
      render(status) {
        return status === 1 ? '已结束' : '未结束'
      }
    },
    {
      title: '开始时间',
      dataIndex: 'start_time',
      render: Utils.formateDate
    },
    {
      title: '结束时间',
      dataIndex: 'end_time',
      render: Utils.formateDate
    },
    {
      title: '订单金额',
      dataIndex: 'total_fee'
    },
    {
      title: '实付金额',
      dataIndex: 'user_pay'
    }
  ]

  const requestList = (pagination) => {
    axios.ajax({
      url: '/order/list',
      data: {
        params: {
          page: pagination
        }
      }
    }).then((res) => {
      let list = res.result.item_list.map((item, index) => {
        item.key = index;
        return item;
      });
      setList(list)
    })
  }

  useEffect(() => {
    requestList(pagination)
  }, [pagination])

  const rowSelection = {
    onChange: (selectedRowKeys, selectedRows) => {
      console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
      setSelectedItem(selectedRows)
      setOrderInfo(selectedRows)
    },
    getCheckboxProps: (record) => ({
      disabled: record.name === 'Disabled User',
      name: record.name,
    }),
  };

  const handleFinish = () => {
    setVisible(true)
  }

  const paginationChange = (pagination) => {
    setPagination(pagination)
  }

  return (
    <div style={{ width: '100%' }}>
      <Card style={{ paddingTop: 20 }}>
        <BaseForm formList={formList} filterSubmit={handleFilter} />
      </Card>
      <Card style={{ marginTop: 10, paddingTop: 15 }}>
        <Button type="primary" onClick={openOrderDetail}>订单详情</Button>
        <Button type="primary" style={{ marginLeft: 10 }} onClick={handleFinish}>结束订单</Button>
      </Card>
      <div className="content-wrap">
        <Card>
          <Table
            columns={columns}
            rowSelection={{
              type: 'radio',
              ...rowSelection,
            }}
            dataSource={list}
            pagination={false}
          />
          <div className="pagination" style={{ float: 'right', marginTop: 20 }}>
            <Pagination onChange={paginationChange} defaultCurrent={1} total={10 * (pagination + 1)} />
          </div>
        </Card>
        <FinishOrder
          visible={visible}
          onCreate={onCreate}
          onCancel={() => {
            setVisible(false);
          }}
          orderInfo={orderInfo}
        />
      </div>
    </div>
  )
}

const FinishOrder = ({ visible, onCreate, onCancel, orderInfo }) => {
  const [form] = Form.useForm()

  return (
    <Modal
      visible={visible}
      title="结束订单"
      okText="确认"
      cancelText="取消"
      onCancel={onCancel}
      onOk={() => {
        form
          .validateFields()
          .then((values) => {
            form.resetFields();
            onCreate(values);
          })
          .catch((info) => {
            console.log('Validate Failed:', info);
          });
      }}
    >
      <Form
        form={form}
        layout="horizontal"
        name="form_in_modal"
        initialValues={{
          modifier: 'public',
        }}
      >
        <Form.Item name="订单编号" label="订单编号">
          {
            orderInfo ? orderInfo[0].order_sn : ''
          }
        </Form.Item>
      </Form>
    </Modal>
  )
}

export default Order